﻿using Newtonsoft.Json;
using System;
using System.Globalization;

namespace ST.Common.Util.Mvc
{
	public class DateTimeJsonConverter : JsonConverter<DateTime>
	{
		private readonly string _format;

		public DateTimeJsonConverter(string format)
		{
			_format = format;
		}

		public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
		{
			writer.WriteValue(value.ToString(_format, CultureInfo.InvariantCulture));
		}

		public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.Date)
			{
				return reader.Value is DateTime dateTime ? dateTime : DateTime.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
			}
			else if (reader.TokenType == JsonToken.String)
			{
				return DateTime.ParseExact(reader.Value.ToString(), _format, CultureInfo.InvariantCulture);
			}
			throw new JsonSerializationException("Unexpected token type: " + reader.TokenType);
		}
	}
}
